#!/bin/bash
# --2022.01.21
# --linjinting

update_config (){
    if [ "$1" == "p70" ];then
        new_base_dir=$(readlink -f "$(pwd)/../../bin/RedisServer")
        new_data_dir=$(readlink -f "$(pwd)/../../DataPacket/RedisData")
        printf "update_config to psm70 \nBaseDir=%s\nDataDir=%s\n" "${new_base_dir}" "${new_data_dir}"

        sed -i "s:^BASEDIR=.*$:BASEDIR=${new_base_dir}:g" redis.init.config
        sed -i "s:^DATADIR=.*$:DATADIR=${new_data_dir}:g" redis.init.config
    else
        echo "pass update config"
    fi
}
# 修改初始化配置文件 redis.init.config
update_config "$1"
# 读取变量
source ./redis.init.config

AUTOSTARTDIR="/etc/init.d"
EXEC="${BASEDIR}/redis-server"
CONF="${BASEDIR}/redis.conf"
CLI="${BASEDIR}/redis-cli"
if [ ! -f "${CONF}" ]; then
	if [ -f redis.conf ]; then
		cp -f redis.conf "${CONF}"
	else
	  echo "redis 配置文件不存在，请检查${CONF}"
	  exit 0
	fi
fi


setting() {
    sed -i "s:^BASEDIR=.*$:BASEDIR=${BASEDIR}:g" redis_init_script
    sed -i "s:^DATADIR=.*$:DATADIR=${DATADIR}:g" redis_init_script

    sed -i "s:^dir.*$:dir ${DATADIR}:g" "${CONF}"

    # 设置 redis-cli 参数、 redis.conf 参数
    if [ "${HOST}" == "" ] || [ "${HOST}" == "127.0.0.1" ]; then
      parma_host=""
    elif [ "${HOST}" == "0.0.0.0" ]; then
      parma_host=""
      sed -i "s:^bind.*$:bind 0.0.0.0:g" "${CONF}"
    else
      parma_host="-h ${HOST}"
      sed -i "s:^bind.*$:bind ${HOST}:g" "${CONF}"
    fi

    if [ "${PORT}" == "" ]; then
      parma_port=""
    elif [ "${PORT}" == "6379" ]; then
      parma_port=""
      sed -i "s:^port.*$:port ${PORT}:g" "${CONF}"
      sed -i "s:^pidfile.*$:pidfile ${DATADIR}/redis_${PORT}.pid:g" "${CONF}"
    else
      parma_port="-p ${PORT}"
      sed -i "s:^port.*$:port ${PORT}:g" "${CONF}"
      sed -i "s:^pidfile.*$:pidfile ${DATADIR}/redis_${PORT}.pid:g" "${CONF}"
    fi

    if  test -z "${PASSWORD}" ; then
      parma_password=""
      sed -i "s:^requirepass.*$:#requirepass:g" "${CONF}"
    else
      parma_password="-a ${PASSWORD}"
      sed -i "s:^requirepass.*$:requirepass ${PASSWORD}:g" "${CONF}"
    fi
    # 组合 redis-cli 参数
    stop_parma="${CLI} ${parma_host} ${parma_port} ${parma_password} shutdown"
    # 组合 redis-server 参数
    start_parma="${EXEC} ${CONF}"
    # pidfile
    PIDFILE=$(cat ${CONF}|grep pidfile |grep '^[^#]'|awk -F" " '{print $NF}')
    if test -z ${PIDFILE}; then
      PIDFILE=/var/run/redis_${REDISPORT}.pid
    fi
}

write_service() {
    printf "########write_service#########\nExecStart=%s\nExecStop=%s\n" "${start_parma}" "${stop_parma}"
    # 设置redis.service 模板内容
    service_temple="
[Unit]
Description=Redis
After=network.target

[Service]
#systemctl status就是根据pid来判断服务的运行状态的
PIDFile=${PIDFILE}
# 以root权限来启动程序
PermissionsStartOnly=true
ExecStart=${start_parma} --daemonize no
ExecStop=${stop_parma}

[Install]
WantedBy=multi-user.target"

    printf "redis.service:%s\n" "${service_temple}"
    echo "${service_temple}" > redis.service
}

function kill_redis() {
    array_pid=$(ps -ef | grep "redis-server" | grep -v grep | awk -F" " '{print $2}')
    for pid in ${array_pid[*]};do
        echo "kill redis for pid $pid"
        kill -9 "${pid}"
        sleep 1s
    done
}

function set_systemd() {
    echo "setting service for systemd"
    if [ ! "$(command -v systemctl)" ];then
        echo "not found command systemctl so ..."
        clean_chkconfig
        set_chkconfig
    fi

    cp -f redis.service /etc/systemd/system/redis.service
    cp -f redis_init_script  "${BASEDIR}/redis.sh"
    chmod +x "${BASEDIR}/redis.sh"
    systemctl daemon-reload
    systemctl enable redis
    systemctl start redis
    systemctl status redis
}

function clean_systemd () {
    systemctl disable redis
    systemctl stop redis
    kill_redis

    rm -rf "/etc/init.d/redis"
    rm -rf "${BASEDIR}/redis.sh"
    rm -rf /etc/systemd/system/redis.service

    systemctl daemon-reload

}

function set_chkconfig() {
    echo "setting service for chkconfig"
    if [ ! "$(command -v chkconfig)" ];then
        echo "not found command chkconfig exit"
        exit 1
    fi

    cp -f redis_init_script  ${AUTOSTARTDIR}/redis
    chmod +x ${AUTOSTARTDIR}/redis
    chkconfig --add redis
    service redis start
}

function clean_chkconfig() {
    echo "clean service for chkconfig"
    if [ ! "$(command -v chkconfig)" ];then
        echo "not found command chkconfig exit"
        exit 1
    fi
    service redis stop
    chkconfig --del redis
    rm -rf ${AUTOSTARTDIR}/redis
    kill_redis

}
set_rc.d() {
    echo "setting service for update-rc.d"
    /etc/init.d/redis stop
    kill_redis
    cp -f redis_init_script  ${AUTOSTARTDIR}/redis
    chmod +x ${AUTOSTARTDIR}/redis
    ##先删除，后添加，防止重复
    update-rc.d -f redis remove
    update-rc.d redis defaults 80
    service redis start
}

f_set_server(){
    setting
    source ../os/os_release.sh
    check_systemctl_type

    if [ ${SYSTEMCTL_TYPE} == 1 ];then
        clean_systemd
        write_service
        set_systemd
    elif [ ${SYSTEMCTL_TYPE} == 2 ]; then
        clean_chkconfig
        set_chkconfig
    # Ubuntu<16.40
    elif [ ${SYSTEMCTL_TYPE} == 3 ]; then
        set_rc.d
	  else
		echo -e "\033[31m unrecognized this system \033[0m"
	  fi
}
f_set_server




